package com.demo.common.ip2region.config;

import com.demo.common.ip2region.constant.LocalResources;
import com.demo.common.ip2region.strategy.Ip2RegionStrategy;
import com.demo.common.ip2region.utils.TempFileUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author：DayDayUp
 * @Create：2023/2/6 9:26
 */
@Configuration
@ConditionalOnClass(Ip2RegionStrategy.class)
@EnableConfigurationProperties(Ip2RegionProperties.class)
public class Ip2RegionAutoConfiguration {

    @Resource
    private Ip2RegionProperties ip2RegionProperties;

    @Bean
    public Ip2RegionStrategy ip2RegionStrategy() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<? extends Ip2RegionStrategy> strategy = ip2RegionProperties.getStrategy();
        Constructor<? extends Ip2RegionStrategy> constructor = strategy.getConstructor(String.class);
        String dbFile = ip2RegionProperties.getDbFile();
        File tempFile = TempFileUtil.loadResource2TempFile(dbFile);
        Ip2RegionStrategy ip2RegionStrategy = constructor.newInstance(tempFile.getAbsolutePath());
        TempFileUtil.deleteTempFiles(LocalResources.IP2REGION,tempFile);
        return ip2RegionStrategy;
    }
}
